<template>
  <div class="cart">
    <van-swipe-cell v-for="item in newCartList" :key="item.id">
      <van-checkbox v-model="item.checked"></van-checkbox>
      <van-card
        :num="item.count"
        :price="item.price"
        :desc="item.Desct"
        :title="item.title"
        class="goods-card"
        :thumb="item.image"
      >
        <template #footer>
          <van-button size="mini" @click="setCount(item, -1)">-</van-button>
          <van-button size="mini" @click="setCount(item, 1)">+</van-button>
        </template>
      </van-card>
      <template #right>
        <van-button
          square
          text="删除"
          type="danger"
          class="delete-button"
          @click="deleteCart(item.id)"
        />
      </template>
    </van-swipe-cell>
    <van-submit-bar :price="allPrice*100" button-text="提交订单">
      <van-checkbox v-model="allCheck">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
export default {
  name: "cart",
  data() {
    return {
      userId: this.$store.state.user.userData.id,
      cartList: [],
      timer: {}
    };
  },
  created() {
    this.getCartList();
  },
  computed: {
    newCartList() {
      return this.cartList.map(item => {
        this.$set(item, "checked", false);
        return item;
      });
    },
    allCheck: {
      // 反选
      get() {
        return this.newCartList.every(item => item.checked);
      },
      // 全选
      set(val) {
        this.newCartList.forEach(item => (item.checked = val));
      }
    },
    allPrice() {
      return this.newCartList.reduce((prev, next) => {
        return (prev += next.checked ? next.count * next.price : 0);
      }, 0);
    }
  },
  methods: {
    getCartList() {
      this.$api
        .getCartList({
          user_id: this.userId
        })
        .then(res => {
          if (res.code === 1) {
            this.cartList = res.data;
          }
          console.log(res);
        });
    },
    setCount(item, count) {
      // 前端count数量++
      item.count = item.count + count;
      clearTimeout(this.timer[item.id]);
      this.timer[item.id] = setTimeout(() => {
        this.$api.setCartCount({
            id: item.id,
            count: item.count
          }).then(res => {
            if (res.code === 1) {
            } else {
              this.getCartList(); // 防止接口崩溃  导致数据不匹配 所以这里重新 获取一遍最新数据
            }
          });
      }, 800);
    },
    deleteCart(id) {
      this.$api.delCart(id).then(res => {
        if (res.code === 1) {
          console.log("删除成功");
          let ind = this.cartList.findIndex(item => item.id === id);
          this.cartList.splice(ind, 1);
        } else {
          alert(res.message);
        }
      });
    }
  }
};
</script>

<style>
.goods-card {
  margin: 0;
  background-color: #fafafa;
}

.delete-button {
  height: 100%;
}
</style>